package cn.mccraft.uide.core.plugin;

import java.util.Locale;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Nonnull;

import org.apache.commons.lang3.Validate;

import com.google.common.collect.Maps;

import cn.mccraft.uide.api.plugin.PluginI18nManager;
import cn.mccraft.uide.api.plugin.UIDEPlugin;
import cn.mccraft.uide.api.util.PluginUtils;
import cn.mccraft.uide.api.util.i18n.I18n;
import cn.mccraft.uide.api.util.i18n.SimpleI18n;
import ro.fortsoft.pf4j.PluginWrapper;

//TODO
public class SimplePluginI18nManager implements PluginI18nManager{
	
	private final Map<PluginWrapper, I18n> pluginI18ns = Maps.newHashMap();
	
	private Locale locale = Locale.getDefault();
	
	public SimplePluginI18nManager() {
		
	}
	
	@Nonnull
	public Locale getLocale() {
		return locale;
	}
	
	public void setLocale(@Nonnull Locale locale) {
		Validate.notNull(locale);
		if(this.locale.equals(locale))
			return;
		this.locale = locale;
	}
	
	@Nonnull
	public String localize(@Nonnull String key) {
		Optional<PluginWrapper> pluginWrapper = PluginUtils.getPlugin();
		if(pluginWrapper.isPresent())
			return getI18n(pluginWrapper.get()).localize(key);
		else 
			return key;
	}
	
	@Nonnull
	public String localize(@Nonnull String key, @Nonnull Object... values) {
		Optional<PluginWrapper> pluginWrapper = PluginUtils.getPlugin();
		if(pluginWrapper.isPresent())
			return getI18n(pluginWrapper.get()).localize(key, values);
		else 
			return key;
	}
	
	public Optional<I18n> getI18n() {
		Optional<PluginWrapper> pluginWrapper = PluginUtils.getPlugin();
		if(pluginWrapper.isPresent())
			return Optional.of(getI18n(pluginWrapper.get()));
		else 
			return Optional.empty();
	}
	
	@Nonnull
	public I18n getI18n(PluginWrapper pluginWrapper) {
		if(pluginI18ns.containsKey(pluginWrapper))
			return pluginI18ns.get(pluginWrapper);
		else {
			UIDEPlugin plugin = (UIDEPlugin) pluginWrapper.getPlugin();
			I18n i18n = new SimpleI18n(plugin.getLanguagePath(), locale, pluginWrapper.getPluginClassLoader());
			pluginI18ns.put(pluginWrapper, i18n);
			return i18n;
		}
	}

}
